<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Paperless-AI RAG</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #6366f1;
            --primary-hover: #4f46e5;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --error-color: #ef4444;
            --text-color: #1f2937;
            --text-secondary: #4b5563;
            --text-tertiary: #9ca3af;
            --bg-color: #ffffff;
            --bg-secondary: #f9fafb;
            --bg-tertiary: #f3f4f6;
            --border-color: #e5e7eb;
            --shadow-color: rgba(0, 0, 0, 0.1);
            --source-bg: #f8fafc;
            --source-border: #e2e8f0;
            --ai-message-bg: #f0f9ff;
            --user-message-bg: #f3f4f6;
            --user-message-text: #111827;
            --assistant-message-text: #0c4a6e;
            --ai-badge-bg: #dbeafe;
            --ai-badge-text: #1e40af;
        }

        [data-theme="dark"] {
            --primary-color: #6366f1;
            --primary-hover: #818cf8;
            --success-color: #34d399;
            --warning-color: #fbbf24;
            --error-color: #f87171;
            --text-color: #f9fafb;
            --text-secondary: #e5e7eb;
            --text-tertiary: #9ca3af;
            --bg-color: #111827;
            --bg-secondary: #1f2937;
            --bg-tertiary: #374151;
            --border-color: #374151;
            --shadow-color: rgba(0, 0, 0, 0.5);
            --source-bg: #1e293b;
            --source-border: #334155;
            --ai-message-bg: #0f172a;
            --user-message-bg: #1f2937;
            --user-message-text: #f9fafb;
            --assistant-message-text: #e0f2fe;
            --ai-badge-bg: #1e3a8a;
            --ai-badge-text: #93c5fd;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
        }

        body {
            background-color: var(--bg-color);
            color: var(--text-color);
            transition: background-color 0.3s ease, color 0.3s ease;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }

        header {
            background-color: var(--bg-secondary);
            border-bottom: 1px solid var(--border-color);
            padding: 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 4px var(--shadow-color);
        }

        .logo {
            display: flex;
            align-items: center;
            font-weight: 700;
            font-size: 1.5rem;
            color: var(--primary-color);
        }

        .logo i {
            margin-right: 0.5rem;
        }

        .header-controls {
            display: flex;
            gap: 1rem;
            align-items: center;
        }

        .theme-toggle {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1.25rem;
            color: var(--text-secondary);
            transition: color 0.2s ease;
        }

        .theme-toggle:hover {
            color: var(--primary-color);
        }

        .ai-model-badge {
            display: flex;
            align-items: center;
            font-size: 0.75rem;
            font-weight: 600;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            background-color: var(--ai-badge-bg);
            color: var(--ai-badge-text);
        }

        .ai-model-badge i {
            margin-right: 0.25rem;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            font-size: 0.875rem;
            color: var(--text-secondary);
        }

        .status-indicator .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 0.5rem;
        }

        .status-dot.online {
            background-color: var(--success-color);
        }

        .status-dot.offline {
            background-color: var(--error-color);
        }

        .status-dot.indexing {
            background-color: var(--warning-color);
        }

        main {
            flex: 1;
            display: flex;
            flex-direction: column;
            max-width: 1024px;
            width: 100%;
            margin: 0 auto;
            padding: 1rem;
        }

        .chat-container {
            flex: 1;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 1rem;
            margin-bottom: 1rem;
            padding-bottom: 1rem;
        }

        .message {
            max-width: 90%;
            padding: 1rem;
            border-radius: 0.5rem;
            line-height: 1.5;
            animation: fadeIn 0.3s ease-in-out;
            box-shadow: 0 1px 2px var(--shadow-color);
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .message.user {
            align-self: flex-end;
            background-color: var(--user-message-bg);
            color: var(--user-message-text);
            border-bottom-right-radius: 0;
        }

        .message.assistant {
            align-self: flex-start;
            background-color: var(--ai-message-bg);
            color: var(--assistant-message-text);
            border-bottom-left-radius: 0;
        }

        .sources-container {
            margin-top: 0.75rem;
            padding-top: 0.75rem;
            border-top: 1px solid var(--source-border);
        }

        .sources-title {
            font-size: 0.875rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: var(--text-secondary);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .sources-toggle {
            background: none;
            border: none;
            cursor: pointer;
            color: var(--text-tertiary);
            font-size: 0.75rem;
            display: flex;
            align-items: center;
        }

        .sources-toggle i {
            margin-left: 0.25rem;
        }

        .source {
            font-size: 0.8125rem;
            padding: 0.5rem;
            background-color: var(--source-bg);
            border: 1px solid var(--source-border);
            border-radius: 0.25rem;
            margin-bottom: 0.5rem;
        }

        .source-title {
            font-weight: 600;
            margin-bottom: 0.25rem;
        }

        .source-meta {
            display: flex;
            justify-content: space-between;
            font-size: 0.75rem;
            color: var(--text-tertiary);
        }

        .input-container {
            position: relative;
            margin-top: auto;
        }

        .message-input {
            width: 100%;
            padding: 1rem;
            padding-right: 4rem;
            border: 1px solid var(--border-color);
            border-radius: 0.5rem;
            background-color: var(--bg-tertiary);
            color: var(--text-color);
            font-size: 1rem;
            resize: none;
            min-height: 60px;
            max-height: 200px;
            transition: border-color 0.2s ease;
            outline: none;
        }

        .message-input:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
        }

        .input-controls {
            position: absolute;
            right: 0.75rem;
            bottom: 0.75rem;
            display: flex;
            gap: 0.5rem;
        }

        .ai-toggle {
            background-color: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: background-color 0.2s ease, color 0.2s ease;
            color: var(--text-tertiary);
        }

        .ai-toggle.active {
            background-color: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }

        .send-button {
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        .send-button:hover {
            background-color: var(--primary-hover);
        }

        .send-button:disabled {
            background-color: var(--text-tertiary);
            cursor: not-allowed;
        }

        .typing-indicator {
            display: flex;
            align-items: center;
            margin-top: 0.5rem;
            font-size: 0.875rem;
            color: var(--text-secondary);
        }

        .typing-indicator .dot {
            width: 4px;
            height: 4px;
            border-radius: 50%;
            background-color: var(--text-secondary);
            margin: 0 2px;
            animation: typing 1.4s infinite both;
        }

        .typing-indicator .dot:nth-child(2) {
            animation-delay: 0.2s;
        }

        .typing-indicator .dot:nth-child(3) {
            animation-delay: 0.4s;
        }

        @keyframes typing {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-4px); }
        }

        .system-message {
            text-align: center;
            font-size: 0.875rem;
            color: var(--text-tertiary);
            margin: 1rem 0;
        }

        .filters {
            padding: 1rem;
            background-color: var(--bg-secondary);
            border-radius: 0.5rem;
            margin-bottom: 1rem;
            border: 1px solid var(--border-color);
        }

        .filters-title {
            font-weight: 600;
            margin-bottom: 0.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
        }

        .filters-content {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
            margin-top: 0.75rem;
        }

        .filter-row {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .filter-group {
            flex: 1;
            min-width: 200px;
        }

        .filter-label {
            display: block;
            font-size: 0.875rem;
            margin-bottom: 0.25rem;
            color: var(--text-secondary);
        }

        .filter-input {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid var(--border-color);
            border-radius: 0.25rem;
            background-color: var(--bg-tertiary);
            color: var(--text-color);
            font-size: 0.875rem;
        }

        .filter-input:focus {
            border-color: var(--primary-color);
            outline: none;
        }

        .api-status {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
            margin-top: 0.5rem;
        }

        .status-badge {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        .status-badge.success {
            background-color: rgba(16, 185, 129, 0.1);
            color: var(--success-color);
            border: 1px solid rgba(16, 185, 129, 0.2);
        }

        .status-badge.warning {
            background-color: rgba(245, 158, 11, 0.1);
            color: var(--warning-color);
            border: 1px solid rgba(245, 158, 11, 0.2);
        }

        .status-badge.error {
            background-color: rgba(239, 68, 68, 0.1);
            color: var(--error-color);
            border: 1px solid rgba(239, 68, 68, 0.2);
        }

        .back-button {
            margin-right: 1rem;
        }

        .back-button a {
            color: var(--primary-color);
            font-size: 1.25rem;
            transition: color 0.2s ease;
            display: flex;
            align-items: center;
        }

        .back-button a:hover {
            color: var(--primary-hover);
        }

        .action-buttons {
            display: flex;
            gap: 0.5rem;
            margin-top: 0.75rem;
            justify-content: flex-end;
        }

        .btn {
            padding: 0.5rem 0.75rem;
            border-radius: 0.25rem;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.25rem;
            transition: all 0.2s ease;
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
            border: none;
        }

        .btn-primary:hover {
            background-color: var(--primary-hover);
        }

        .btn-outline {
            background-color: transparent;
            color: var(--text-color);
            border: 1px solid var(--border-color);
        }

        .btn-outline:hover {
            background-color: var(--bg-tertiary);
        }

        .btn:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }

        footer {
            text-align: center;
            padding: 1rem;
            font-size: 0.875rem;
            color: var(--text-tertiary);
            background-color: var(--bg-secondary);
            border-top: 1px solid var(--border-color);
        }

        @media (max-width: 768px) {
            .filter-row {
                flex-direction: column;
                gap: 0.5rem;
            }

            .message {
                max-width: 95%;
            }
        }

        /* Markdown styling */
        .markdown {
            line-height: 1.6;
        }

        .markdown p {
            margin-bottom: 0.75rem;
        }

        .markdown p:last-child {
            margin-bottom: 0;
        }

        .markdown ul, .markdown ol {
            padding-left: 1.5rem;
            margin: 0.75rem 0;
        }

        .markdown li {
            margin-bottom: 0.25rem;
        }

        .markdown h1, .markdown h2, .markdown h3, .markdown h4 {
            margin: 1rem 0 0.5rem;
            font-weight: 600;
        }

        .markdown h1 {
            font-size: 1.5rem;
        }

        .markdown h2 {
            font-size: 1.25rem;
        }

        .markdown h3 {
            font-size: 1.125rem;
        }

        .markdown h4 {
            font-size: 1rem;
        }

        .markdown code {
            font-family: monospace;
            background-color: var(--source-bg);
            padding: 0.125rem 0.25rem;
            border-radius: 0.25rem;
            font-size: 0.9em;
        }

        .markdown pre {
            background-color: var(--source-bg);
            padding: 0.75rem;
            border-radius: 0.25rem;
            overflow-x: auto;
            margin: 0.75rem 0;
        }

        .markdown pre code {
            background-color: transparent;
            padding: 0;
        }

        .hidden {
            display: none;
        }

        #error-message {
            color: var(--error-color);
            font-size: 0.875rem;
            margin-top: 0.5rem;
            padding: 0.5rem;
            border-radius: 0.25rem;
            background-color: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.2);
            animation: fadeIn 0.3s ease-in-out;
        }
    </style>
</head>
<body>
<header>
        <div class="back-button">
            <a href="/dashboard" title="Back to Dashboard">
                <i class="fas fa-arrow-left"></i>
            </a>
        </div>
        <div class="logo">
            <i class="fas fa-search"></i>
            Paperless-AI RAG Chat
        </div>
        <div class="header-controls">
            <div class="ai-model-badge" id="ai-model-badge">
                <i class="fas fa-robot"></i>
                <span id="ai-model-name">AI: Loading...</span>
            </div>
            <div class="status-indicator">
                <div class="status-dot offline" id="status-indicator"></div>
                <span id="status-text">Connecting...</span>
            </div>
            <button class="theme-toggle" id="theme-toggle">
                <i class="fas fa-moon"></i>
            </button>
        </div>
    </header>

    <main>
        <div class="filters">
            <div class="filters-title" id="filters-toggle">
                <span>API Status</span>
                <i class="fas fa-chevron-down"></i>
            </div>
            <div class="filters-content" id="filters-content">
                <div class="filter-row" style="display: none;">
                    <div class="filter-group">
                        <label class="filter-label" for="date-from">From Date</label>
                        <input type="date" id="date-from" class="filter-input">
                    </div>
                    <div class="filter-group">
                        <label class="filter-label" for="date-to">To Date</label>
                        <input type="date" id="date-to" class="filter-input">
                    </div>
                    <div class="filter-group">
                        <label class="filter-label" for="correspondent">Sender/Recipient</label>
                        <input type="text" id="correspondent" class="filter-input" placeholder="Name of sender/recipient">
                    </div>
                </div>

                <div class="api-status" id="api-status">
                    <!-- Status badges will be loaded dynamically -->
                </div>

                <div class="action-buttons">
                    <button class="btn btn-outline" id="check-updates-btn">
                        <i class="fas fa-sync-alt"></i>
                        Check for Updates
                    </button>
                    <button class="btn btn-primary" id="start-indexing-btn">
                        <i class="fas fa-database"></i>
                        Start Indexing
                    </button>
                </div>
            </div>
        </div>

        <div class="chat-container" id="chat-container">
            <div class="system-message">
                Welcome to Paperless-AI RAG Chat! Ask a question about your documents.
            </div>
        </div>

        <div id="error-message" class="hidden"></div>

        <div class="typing-indicator hidden" id="typing-indicator">
            <span>Search in progress</span>
            <div class="dot"></div>
            <div class="dot"></div>
            <div class="dot"></div>
        </div>

        <div class="input-container">
            <textarea 
                class="message-input" 
                id="message-input" 
                placeholder="Ask a question about your documents..." 
                rows="1"
                aria-label="Enter message"></textarea>
            <div class="input-controls">
                <button class="ai-toggle active" style="visibility: hidden;" id="ai-toggle" aria-label="Toggle AI" title="Enable/disable AI response">
                    <i class="fas fa-robot"></i>
                </button>
                <button class="send-button" id="send-button" aria-label="Send message">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </div>
        </div>
    </main>

    <footer>
        &copy; 2025 Paperless-AI - RAG | Document search with AI
    </footer>

    <script>
        // DOM Elements
        const themeToggle = document.getElementById('theme-toggle');
        const statusIndicator = document.getElementById('status-indicator');
        const statusText = document.getElementById('status-text');
        const apiStatus = document.getElementById('api-status');
        const chatContainer = document.getElementById('chat-container');
        const messageInput = document.getElementById('message-input');
        const sendButton = document.getElementById('send-button');
        const typingIndicator = document.getElementById('typing-indicator');
        const filtersToggle = document.getElementById('filters-toggle');
        const filtersContent = document.getElementById('filters-content');
        const checkUpdatesBtn = document.getElementById('check-updates-btn');
        const startIndexingBtn = document.getElementById('start-indexing-btn');
        const errorMessage = document.getElementById('error-message');
        const dateFrom = document.getElementById('date-from');
        const dateTo = document.getElementById('date-to');
        const correspondent = document.getElementById('correspondent');
        const aiToggle = document.getElementById('ai-toggle');
        const aiModelBadge = document.getElementById('ai-model-badge');
        const aiModelName = document.getElementById('ai-model-name');

        // State
        let darkMode = localStorage.getItem('darkMode') === 'true';
        let useAI = localStorage.getItem('useAI') !== 'false'; // Default: true
        let isConnected = false; // Track connection status

        // Initialize
        document.addEventListener('DOMContentLoaded', () => {
            updateTheme();
            updateAIToggle();
            autoResizeTextarea();
            messageInput.addEventListener('input', autoResizeTextarea);
            
            // Initialize status badges to "connecting" state
            updateStatusBadgesLoading();
            
            // Perform initial status check
            checkStatus();
            
            // Initialize event listeners
            sendButton.addEventListener('click', sendMessage);
            messageInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
            
            themeToggle.addEventListener('click', () => {
                darkMode = !darkMode;
                localStorage.setItem('darkMode', darkMode);
                updateTheme();
            });
            
            aiToggle.addEventListener('click', () => {
                useAI = !useAI;
                localStorage.setItem('useAI', useAI);
                updateAIToggle();
            });
            
            filtersToggle.addEventListener('click', () => {
                filtersContent.classList.toggle('hidden');
                const icon = filtersToggle.querySelector('i');
                if (filtersContent.classList.contains('hidden')) {
                    icon.className = 'fas fa-chevron-down';
                } else {
                    icon.className = 'fas fa-chevron-up';
                }
            });
            
            checkUpdatesBtn.addEventListener('click', async () => {
                checkUpdatesBtn.disabled = true;
                checkUpdatesBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Checking...';
                
                try {
                    const response = await fetch('/api/rag/index/check');
                    
                    if (response.ok) {
                        const data = await response.json();
                        showSystemMessage(`Status: ${data.message}`);
                        isConnected = true;
                        updateStatusIndicator('online', 'Online');
                    } else {
                        showError('Error checking status');
                        isConnected = false;
                        updateStatusIndicator('offline', 'Offline');
                        updateStatusBadgesOffline();
                    }
                } catch (error) {
                    showError(`Connection error: ${error.message}`);
                    isConnected = false;
                    updateStatusIndicator('offline', 'Offline');
                    updateStatusBadgesOffline();
                } finally {
                    checkUpdatesBtn.disabled = false;
                    checkUpdatesBtn.innerHTML = '<i class="fas fa-sync-alt"></i> Check for Updates';
                }
            });
            
            startIndexingBtn.addEventListener('click', async () => {
                startIndexingBtn.disabled = true;
                startIndexingBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Starting...';
                
                try {
                    const response = await fetch('/api/rag/index', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            force: true,
                            background: true
                        })
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        showSystemMessage(`Indexing started: ${data.status}`);
                        updateStatusIndicator('indexing', 'Indexing in progress');
                        
                        // Update status badges to show indexing in progress
                        addStatusBadge(false, 'Indexing', 'In Progress', 'warning');
                        
                        isConnected = true;
                    } else {
                        showError('Error starting indexing');
                        isConnected = false;
                        updateStatusIndicator('offline', 'Offline');
                        updateStatusBadgesOffline();
                    }
                } catch (error) {
                    showError(`Connection error: ${error.message}`);
                    isConnected = false;
                    updateStatusIndicator('offline', 'Offline');
                    updateStatusBadgesOffline();
                } finally {
                    startIndexingBtn.disabled = false;
                    startIndexingBtn.innerHTML = '<i class="fas fa-database"></i> Start Indexing';
                }
            });

            // Poll for status updates every 10 seconds
            setInterval(checkStatus, 10000);
        });

        function updateTheme() {
            if (darkMode) {
                document.documentElement.setAttribute('data-theme', 'dark');
                themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
            } else {
                document.documentElement.removeAttribute('data-theme');
                themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
            }
        }

        function updateAIToggle() {
            if (useAI) {
                aiToggle.classList.add('active');
                aiToggle.title = 'Disable AI response';
            } else {
                aiToggle.classList.remove('active');
                aiToggle.title = 'Enable AI response';
            }
        }

        function autoResizeTextarea() {
            messageInput.style.height = 'auto';
            messageInput.style.height = (messageInput.scrollHeight) + 'px';
        }

        // Function to check RAG service status
        async function checkStatus() {
            try {
                const response = await fetch('/api/rag/status');
                if (response.ok) {
                    const data = await response.json();
                    isConnected = true;
                    updateStatus(data);
                } else {
                    isConnected = false;
                    updateStatusIndicator('offline', 'Offline');
                    updateStatusBadgesOffline();
                }
            } catch (error) {
                console.error('Error checking status:', error);
                isConnected = false;
                updateStatusIndicator('offline', 'Offline');
                updateStatusBadgesOffline();
            }
        }

        function updateStatus(statusData) {
            // Update AI model info
            if (statusData.ai_status === 'ok') {
                const modelName = statusData.ai_model.toUpperCase();
                aiModelName.textContent = `AI MODEL: ${modelName}`;
            } else {
                aiModelName.textContent = 'AI: Not available';
            }
            
            // Update status indicator
            if (!statusData.server_up) {
                updateStatusIndicator('offline', 'Offline');
                updateStatusBadgesOffline();
                return;
            }
            
            if (statusData.indexing_status && statusData.indexing_status.running) {
                updateStatusIndicator('indexing', 'Indexing in progress');
            } else if (statusData.index_ready) {
                updateStatusIndicator('online', 'Ready');
            } else if (statusData.data_loaded) {
                updateStatusIndicator('indexing', 'Creating index');
            } else {
                updateStatusIndicator('indexing', 'Loading data');
            }
            
            // Update API status badges
            updateStatusBadges(statusData);
        }

        function updateStatusIndicator(status, text) {
            statusIndicator.className = `status-dot ${status}`;
            statusText.textContent = text;
        }

        function updateStatusBadgesLoading() {
            apiStatus.innerHTML = '';
            addStatusBadge(false, 'Server', 'Connecting...', 'warning');
            addStatusBadge(false, 'Data', 'Pending', 'warning');
            addStatusBadge(false, 'Index', 'Pending', 'warning');
        }

        function updateStatusBadgesOffline() {
            apiStatus.innerHTML = '';
            addStatusBadge(false, 'Server', 'Offline', 'error');
            addStatusBadge(false, 'Data', 'Unknown', 'error');
            addStatusBadge(false, 'Index', 'Unknown', 'error');
        }

        function updateStatusBadges(statusData) {
            apiStatus.innerHTML = '';
            
            // Server Status
            addStatusBadge(
                statusData.server_up,
                'Server',
                statusData.server_up ? 'Online' : 'Offline'
            );
            
            // Data Status
            if (statusData.data_loaded !== undefined) {
                addStatusBadge(
                    statusData.data_loaded,
                    'Data',
                    statusData.data_loaded ? 'Loaded' : 'Not loaded'
                );
            }
            
            // Index Status
            if (statusData.index_ready !== undefined) {
                addStatusBadge(
                    statusData.index_ready,
                    'Index',
                    statusData.index_ready ? 'Ready' : 'Not ready'
                );
            }
            
            // Indexing Status
            if (statusData.indexing_status && statusData.indexing_status.running) {
                addStatusBadge(
                    false,
                    'Indexing',
                    'In Progress',
                    'warning'
                );
            }
            
            // Document Count
            if (statusData.indexing_status && statusData.indexing_status.documents_count > 0) {
                addStatusBadge(
                    true,
                    'Documents',
                    statusData.indexing_status.documents_count.toString(),
                    'success'
                );
            } else if (statusData.indexing_status) {
                // If documents_count is 0 but we're connected, show as warning
                addStatusBadge(
                    false,
                    'Documents',
                    statusData.indexing_status.documents_count.toString(),
                    'warning'
                );
            }
        }
        
        function addStatusBadge(isSuccess, label, value, forceStatus = null) {
            const status = forceStatus || (isSuccess ? 'success' : 'error');
            const icon = status === 'success' ? 'check-circle' : 
                        status === 'warning' ? 'exclamation-triangle' : 'times-circle';
            
            const badge = document.createElement('div');
            badge.className = `status-badge ${status}`;
            badge.innerHTML = `
                <i class="fas fa-${icon}"></i>
                <span>${label}: ${value}</span>
            `;
            apiStatus.appendChild(badge);
        }

        function sendMessage() {
            const questionText = messageInput.value.trim();
            if (!questionText) return;
            
            // Check if we're connected before sending
            if (!isConnected) {
                showError("Cannot send message: Server is offline. Please check your connection.");
                return;
            }
            
            // Clear input and resize
            messageInput.value = '';
            messageInput.style.height = 'auto';
            
            // Add user message to chat
            addUserMessage(questionText);
            
            // Show typing indicator
            typingIndicator.classList.remove('hidden');
            
            // Clear error message
            errorMessage.classList.add('hidden');
            
            // Get filter values
            const fromDate = dateFrom.value;
            const toDate = dateTo.value;
            const correspondentValue = correspondent.value.trim();
            
            // Prepare request
            const endpoint = '/api/rag/ask';
            
            fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    question: questionText,
                    useAI: useAI,
                    from_date: fromDate || undefined,
                    to_date: toDate || undefined,
                    correspondent: correspondentValue || undefined
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Server responded with ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                // Hide typing indicator
                typingIndicator.classList.add('hidden');
                
                // Display answer with sources
                addAssistantMessage(data.answer, data.sources, data.model);
                
                // Update connection status
                isConnected = true;
                updateStatusIndicator('online', 'Online');
            })
            .catch(error => {
                // Hide typing indicator
                typingIndicator.classList.add('hidden');
                
                // Show error message
                showError(`Error: ${error.message}`);
                
                // Update connection status if there was an error
                isConnected = false;
                updateStatusIndicator('offline', 'Offline');
                updateStatusBadgesOffline();
                
                // Schedule an immediate status check
                setTimeout(checkStatus, 1000);
            });
        }

        function addUserMessage(message) {
            const messageElement = document.createElement('div');
            messageElement.className = 'message user';
            messageElement.textContent = message;
            chatContainer.appendChild(messageElement);
            scrollToBottom();
        }

        function addAssistantMessage(message, sources = [], modelUsed = null) {
            const messageElement = document.createElement('div');
            messageElement.className = 'message assistant';
            
            // Format message with markdown
            let formattedMessage = message.replace(/\n\n/g, '</p><p>').replace(/\n/g, '<br>');
            if (!formattedMessage.startsWith('<p>')) formattedMessage = '<p>' + formattedMessage;
            if (!formattedMessage.endsWith('</p>')) formattedMessage += '</p>';
            
            let html = `<div class="markdown">${formattedMessage}</div>`;
            
            // Add model info if available
            if (modelUsed) {
                html += `<div style="font-size: 0.75rem; margin-top: 0.5rem; color: var(--text-tertiary);">
                            <i class="fas fa-robot"></i> Answered with ${modelUsed}
                        </div>`;
            }
            
            // Add sources if available
            if (sources && sources.length > 0) {
                html += `<div class="sources-container">
                            <div class="sources-title">
                                <span>Sources (${sources.length})</span>
                                <button class="sources-toggle" data-expanded="false">
                                    Show all <i class="fas fa-chevron-down"></i>
                                </button>
                            </div>
                            <div class="sources-list">`;
                
                sources.forEach((source, index) => {
                    const date = source.date ? new Date(source.date).toLocaleDateString('en-US') : 'Unknown';
                    const hidden = index > 0 ? ' hidden' : '';
                    
                    html += `
                        <div class="source${hidden}" data-index="${index}">
                            <div class="source-title">${source.title || 'Unknown Title'}</div>
                            <p>${source.snippet || 'No excerpt available'}</p>
                            <div class="source-meta">
                                <span>${source.correspondent || 'Unknown Sender'}</span>
                                <span>${date}</span>
                            </div>
                        </div>
                    `;
                });
                
                html += `</div></div>`;
            }
            
            messageElement.innerHTML = html;
            chatContainer.appendChild(messageElement);
            
            // Add event listener for sources toggle
            const toggleBtn = messageElement.querySelector('.sources-toggle');
            if (toggleBtn) {
                toggleBtn.addEventListener('click', () => {
                    const sourcesList = messageElement.querySelector('.sources-list');
                    const sources = sourcesList.querySelectorAll('.source');
                    const isExpanded = toggleBtn.getAttribute('data-expanded') === 'true';
                    
                    if (isExpanded) {
                        // Collapse
                        sources.forEach((source, index) => {
                            if (index > 0) source.classList.add('hidden');
                        });
                        toggleBtn.innerHTML = 'Show all <i class="fas fa-chevron-down"></i>';
                        toggleBtn.setAttribute('data-expanded', 'false');
                    } else {
                        // Expand
                        sources.forEach(source => source.classList.remove('hidden'));
                        toggleBtn.innerHTML = 'Hide <i class="fas fa-chevron-up"></i>';
                        toggleBtn.setAttribute('data-expanded', 'true');
                    }
                });
            }
            
            scrollToBottom();
        }

        function showSystemMessage(message) {
            const systemMessage = document.createElement('div');
            systemMessage.className = 'system-message';
            systemMessage.textContent = message;
            chatContainer.appendChild(systemMessage);
            scrollToBottom();
        }

        function showError(message) {
            errorMessage.textContent = message;
            errorMessage.classList.remove('hidden');
        }

        function scrollToBottom() {
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
    </script>
</body>
</html>